<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>统计分析 - Netty See</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
        }
        
        .stats-card h3 {
            font-size: 2.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .stats-card p {
            margin-bottom: 0;
            opacity: 0.9;
        }
        
        /* 关键：固定图表容器高度，防止Y轴变化影响页面布局 */
        .chart-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            height: 420px; /* 固定高度 */
            min-height: 420px; /* 最小高度 */
            max-height: 420px; /* 最大高度 */
            overflow: hidden; /* 防止内容溢出 */
            position: relative;
        }
        
        .chart-wrapper {
            height: 350px; /* 为图表预留固定空间 */
            width: 100%;
            position: relative;
        }
        
        .chart-wrapper canvas {
            max-height: 350px !important; /* 强制限制canvas高度 */
            max-width: 100% !important;
        }
        
        .table-container {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .metric-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
            margin: 2px;
        }
        
        .metric-success { background-color: #d4edda; color: #155724; }
        .metric-warning { background-color: #fff3cd; color: #856404; }
        .metric-danger { background-color: #f8d7da; color: #721c24; }
        .metric-info { background-color: #d1ecf1; color: #0c5460; }
        
        .refresh-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
        }
        
        .time-selector {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .chart-status {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 0.8rem;
            padding: 4px 8px;
            border-radius: 4px;
            background-color: #28a745;
            color: white;
        }
        
        .chart-status.locked {
            background-color: #ffc107;
            color: #000;
        }
        
        .loading-spinner {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            display: none;
        }
        
        .loading-spinner.show {
            display: block;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fas fa-chart-line me-2"></i>Netty See - 统计分析
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="/"><i class="fas fa-home me-1"></i>首页</a>
                <a class="nav-link" href="/channels"><i class="fas fa-network-wired me-1"></i>连接</a>
                <a class="nav-link" href="/performance"><i class="fas fa-tachometer-alt me-1"></i>性能</a>
                <a class="nav-link active" href="/statistics"><i class="fas fa-chart-bar me-1"></i>统计</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- 时间选择器和控制面板 -->
        <div class="time-selector">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="mb-0">
                        <i class="fas fa-clock me-2"></i>时间范围
                        <span id="dataStatus" class="badge bg-success ms-2">实时</span>
                        <small id="lastUpdate" class="text-muted ms-2"></small>
                    </h5>
                </div>
                <div class="col-md-6 text-end">
                    <div class="btn-group me-2" role="group">
                        <button type="button" class="btn btn-outline-primary" onclick="setTimeRange(5)">5分钟</button>
                        <button type="button" class="btn btn-outline-primary" onclick="setTimeRange(30)">30分钟</button>
                        <button type="button" class="btn btn-primary" onclick="setTimeRange(60)">1小时</button>
                        <button type="button" class="btn btn-outline-primary" onclick="setTimeRange(360)">6小时</button>
                    </div>
                    <button type="button" class="btn btn-outline-warning" onclick="toggleYAxisLock()" id="lockBtn">
                        <i class="fas fa-lock"></i> 锁定Y轴
                    </button>
                    <button type="button" class="btn btn-outline-success" onclick="refreshData()">
                        <i class="fas fa-sync-alt"></i> 刷新
                    </button>
                </div>
            </div>
        </div>

        <!-- 实时统计卡片 -->
        <div class="row">
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="activeConnections">0</h3>
                    <p><i class="fas fa-plug me-2"></i>活跃连接</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="totalRequests">0</h3>
                    <p><i class="fas fa-exchange-alt me-2"></i>总请求数</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="avgResponseTime">0ms</h3>
                    <p><i class="fas fa-clock me-2"></i>平均响应时间</p>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card">
                    <h3 id="errorRate">0%</h3>
                    <p><i class="fas fa-exclamation-triangle me-2"></i>错误率</p>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <h5><i class="fas fa-chart-line me-2"></i>连接数趋势</h5>
                    <div class="chart-status" id="connectionStatus">稳定</div>
                    <div class="loading-spinner" id="connectionLoading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                    <div class="chart-wrapper">
                        <canvas id="connectionChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h5><i class="fas fa-tachometer-alt me-2"></i>吞吐量趋势</h5>
                    <div class="chart-status" id="throughputStatus">稳定</div>
                    <div class="loading-spinner" id="throughputLoading">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                    <div class="chart-wrapper">
                        <canvas id="throughputChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="chart-container">
                    <h5><i class="fas fa-stopwatch me-2"></i>响应时间分布</h5>
                    <div class="chart-wrapper">
                        <canvas id="responseTimeChart"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="chart-container">
                    <h5><i class="fas fa-bug me-2"></i>错误统计</h5>
                    <div class="chart-wrapper">
                        <canvas id="errorChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 应用统计表格 -->
        <div class="table-container">
            <h5><i class="fas fa-apps me-2"></i>应用统计</h5>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>应用名称</th>
                            <th>当前连接</th>
                            <th>峰值连接</th>
                            <th>总请求数</th>
                            <th>成功率</th>
                            <th>平均响应时间</th>
                            <th>吞吐量</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody id="applicationStatsTable">
                        <!-- 动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 刷新按钮 -->
    <button class="btn btn-primary btn-lg refresh-btn" onclick="refreshData()" title="刷新数据">
        <i class="fas fa-sync-alt"></i>
    </button>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let currentTimeRange = 60; // 默认1小时
        let charts = {};
        let yAxisLocked = true; // 默认锁定Y轴
        let refreshInterval;
        
        // Y轴管理器 - 简化版本，专注于稳定性
        const yAxisManager = {
            connection: { max: 500, locked: true },
            throughput: { max: 1000, locked: true },
            
            getRange(type, values) {
                if (this[type].locked) {
                    return this[type].max;
                }
                
                const maxValue = Math.max(...values.filter(v => v != null && !isNaN(v)));
                if (maxValue <= 0) return this[type].max;
                
                // 使用预定义的范围级别
                const levels = [100, 200, 500, 1000, 2000, 5000, 10000];
                const newMax = levels.find(level => level >= maxValue * 1.3) || maxValue * 1.5;
                
                return newMax;
            },
            
            setLocked(locked) {
                this.connection.locked = locked;
                this.throughput.locked = locked;
            }
        };
        
        // 初始化图表
        function initCharts() {
            // 连接数趋势图
            const connectionCtx = document.getElementById('connectionChart').getContext('2d');
            charts.connection = new Chart(connectionCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '活跃连接',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.1)',
                        tension: 0.3,
                        fill: true
                    }, {
                        label: '峰值连接',
                        data: [],
                        borderColor: 'rgb(255, 99, 132)',
                        backgroundColor: 'rgba(255, 99, 132, 0.1)',
                        tension: 0.3,
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            min: 0,
                            max: 500, // 固定初始最大值
                            title: {
                                display: true,
                                text: '连接数'
                            }
                        }
                    },
                    elements: {
                        point: {
                            radius: 3,
                            hoverRadius: 5
                        }
                    }
                }
            });

            // 吞吐量趋势图
            const throughputCtx = document.getElementById('throughputChart').getContext('2d');
            charts.throughput = new Chart(throughputCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'TPS',
                        data: [],
                        borderColor: 'rgb(54, 162, 235)',
                        backgroundColor: 'rgba(54, 162, 235, 0.1)',
                        tension: 0.3,
                        fill: true
                    }, {
                        label: 'QPS',
                        data: [],
                        borderColor: 'rgb(255, 206, 86)',
                        backgroundColor: 'rgba(255, 206, 86, 0.1)',
                        tension: 0.3,
                        fill: false
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            beginAtZero: true,
                            min: 0,
                            max: 1000, // 固定初始最大值
                            title: {
                                display: true,
                                text: 'TPS/QPS'
                            }
                        }
                    },
                    elements: {
                        point: {
                            radius: 3,
                            hoverRadius: 5
                        }
                    }
                }
            });

            // 响应时间分布图
            const responseTimeCtx = document.getElementById('responseTimeChart').getContext('2d');
            charts.responseTime = new Chart(responseTimeCtx, {
                type: 'bar',
                data: {
                    labels: ['0-10ms', '10-50ms', '50-100ms', '100-500ms', '500ms+'],
                    datasets: [{
                        label: '请求数量',
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: [
                            'rgba(75, 192, 192, 0.8)',
                            'rgba(54, 162, 235, 0.8)',
                            'rgba(255, 206, 86, 0.8)',
                            'rgba(255, 159, 64, 0.8)',
                            'rgba(255, 99, 132, 0.8)'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // 错误统计图
            const errorCtx = document.getElementById('errorChart').getContext('2d');
            charts.error = new Chart(errorCtx, {
                type: 'doughnut',
                data: {
                    labels: ['成功', '错误'],
                    datasets: [{
                        data: [100, 0],
                        backgroundColor: [
                            'rgba(75, 192, 192, 0.8)',
                            'rgba(255, 99, 132, 0.8)'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
        
        // 设置时间范围
        function setTimeRange(minutes) {
            currentTimeRange = minutes;
            
            // 更新按钮状态
            document.querySelectorAll('.btn-group .btn').forEach(btn => {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-primary');
            });
            event.target.classList.remove('btn-outline-primary');
            event.target.classList.add('btn-primary');
            
            // 刷新数据
            refreshData();
        }
        
        // 切换Y轴锁定状态
        function toggleYAxisLock() {
            yAxisLocked = !yAxisLocked;
            yAxisManager.setLocked(yAxisLocked);
            
            const lockBtn = document.getElementById('lockBtn');
            const connectionStatus = document.getElementById('connectionStatus');
            const throughputStatus = document.getElementById('throughputStatus');
            
            if (yAxisLocked) {
                lockBtn.innerHTML = '<i class="fas fa-lock"></i> 已锁定';
                lockBtn.classList.remove('btn-outline-warning');
                lockBtn.classList.add('btn-warning');
                connectionStatus.textContent = '锁定';
                connectionStatus.classList.add('locked');
                throughputStatus.textContent = '锁定';
                throughputStatus.classList.add('locked');
            } else {
                lockBtn.innerHTML = '<i class="fas fa-unlock"></i> 自动';
                lockBtn.classList.remove('btn-warning');
                lockBtn.classList.add('btn-outline-warning');
                connectionStatus.textContent = '自动';
                connectionStatus.classList.remove('locked');
                throughputStatus.textContent = '自动';
                throughputStatus.classList.remove('locked');
            }
            
            console.log('Y轴锁定状态:', yAxisLocked ? '已锁定' : '自动调整');
        }
        
        // 显示加载状态
        function showLoading(chartType) {
            const loadingElement = document.getElementById(chartType + 'Loading');
            if (loadingElement) {
                loadingElement.classList.add('show');
            }
        }
        
        // 隐藏加载状态
        function hideLoading(chartType) {
            const loadingElement = document.getElementById(chartType + 'Loading');
            if (loadingElement) {
                loadingElement.classList.remove('show');
            }
        }
        
        // 刷新数据
        function refreshData() {
            console.log('刷新数据...');
            
            // 旋转刷新按钮
            const refreshBtn = document.querySelector('.refresh-btn i');
            refreshBtn.classList.add('fa-spin');
            
            // 显示加载状态
            showLoading('connection');
            showLoading('throughput');
            
            // 尝试加载真实数据，失败时使用模拟数据
            Promise.all([
                loadRealTimeStats(),
                loadTrendData()
            ]).catch(() => {
                console.warn('无法加载真实数据，使用模拟数据');
                useMockData();
            }).finally(() => {
                refreshBtn.classList.remove('fa-spin');
                hideLoading('connection');
                hideLoading('throughput');
                updateLastUpdateTime();
            });
        }
        
        // 加载实时统计
        function loadRealTimeStats() {
            return fetch('/api/statistics/realtime')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    updateRealTimeStats(data);
                    updateDataStatus(true);
                })
                .catch(error => {
                    console.error('Error loading real-time stats:', error);
                    throw error;
                });
        }
        
        // 加载趋势数据
        function loadTrendData() {
            return fetch(`/api/statistics/recent/${currentTimeRange}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data && Array.isArray(data.data)) {
                        updateTrendCharts(data.data);
                    } else if (Array.isArray(data)) {
                        updateTrendCharts(data);
                    } else {
                        throw new Error('Invalid data format');
                    }
                })
                .catch(error => {
                    console.error('Error loading trend data:', error);
                    throw error;
                });
        }
        
        // 更新实时统计
        function updateRealTimeStats(data) {
            document.getElementById('activeConnections').textContent = (data.activeConnections || 0).toLocaleString();
            document.getElementById('totalRequests').textContent = (data.totalRequests || 0).toLocaleString();
            document.getElementById('avgResponseTime').textContent = (data.avgResponseTime || 0).toFixed(1) + 'ms';
            document.getElementById('errorRate').textContent = (data.errorRate || 0).toFixed(1) + '%';
        }
        
        // 更新趋势图表
        function updateTrendCharts(data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.warn('No trend data available');
                return;
            }
            
            // 限制数据点数量
            const maxDataPoints = 50;
            const limitedData = data.slice(-maxDataPoints);
            
            const labels = limitedData.map(item => {
                const date = new Date(item.windowStart || item.timestamp || new Date());
                return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            });

            // 更新连接数趋势
            const connectionValues = limitedData.flatMap(item => [
                item.activeConnections || 0, 
                item.peakConnections || 0
            ]);
            const connectionMax = yAxisManager.getRange('connection', connectionValues);
            
            charts.connection.data.labels = labels;
            charts.connection.data.datasets[0].data = limitedData.map(item => item.activeConnections || 0);
            charts.connection.data.datasets[1].data = limitedData.map(item => item.peakConnections || 0);
            charts.connection.options.scales.y.max = connectionMax;
            charts.connection.update('none');

            // 更新吞吐量趋势
            const throughputValues = limitedData.flatMap(item => [
                item.tps || 0, 
                item.qps || 0
            ]);
            const throughputMax = yAxisManager.getRange('throughput', throughputValues);
            
            charts.throughput.data.labels = labels;
            charts.throughput.data.datasets[0].data = limitedData.map(item => item.tps || 0);
            charts.throughput.data.datasets[1].data = limitedData.map(item => item.qps || 0);
            charts.throughput.options.scales.y.max = throughputMax;
            charts.throughput.update('none');

            // 更新响应时间分布
            updateResponseTimeDistribution(limitedData);
            
            // 更新错误统计
            updateErrorStats(limitedData);
        }
        
        // 更新响应时间分布
        function updateResponseTimeDistribution(data) {
            if (data.length === 0) return;
            
            const latestData = data[data.length - 1];
            const avgResponseTime = latestData.avgResponseTime || 50;
            const totalRequests = latestData.totalRequests || 1000;
            
            // 根据平均响应时间模拟分布
            let distribution;
            if (avgResponseTime < 20) {
                distribution = [0.7, 0.2, 0.05, 0.03, 0.02];
            } else if (avgResponseTime < 50) {
                distribution = [0.4, 0.4, 0.1, 0.05, 0.05];
            } else if (avgResponseTime < 100) {
                distribution = [0.2, 0.3, 0.3, 0.15, 0.05];
            } else {
                distribution = [0.1, 0.2, 0.3, 0.3, 0.1];
            }
            
            charts.responseTime.data.datasets[0].data = distribution.map(ratio => 
                Math.floor(totalRequests * ratio)
            );
            charts.responseTime.update('none');
        }
        
        // 更新错误统计
        function updateErrorStats(data) {
            if (data.length === 0) return;
            
            const latestData = data[data.length - 1];
            const totalRequests = latestData.totalRequests || 0;
            const successfulRequests = latestData.successfulRequests || totalRequests;
            const errorRequests = totalRequests - successfulRequests;
            
            charts.error.data.datasets[0].data = [
                Math.max(0, successfulRequests), 
                Math.max(0, errorRequests)
            ];
            charts.error.update('none');
        }
        

        

        

        
        // 更新应用统计表格
        function updateApplicationTable(data) {
            const tbody = document.getElementById('applicationStatsTable');
            if (!tbody) return;
            
            tbody.innerHTML = '';
            
            if (!Array.isArray(data) || data.length === 0) {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td colspan="8" class="text-center text-muted">
                        <i class="fas fa-info-circle me-2"></i>暂无应用统计数据
                    </td>
                `;
                tbody.appendChild(row);
                return;
            }

            data.forEach(app => {
                const row = document.createElement('tr');
                const statusBadge = getStatusBadge(app.avgResponseTime || 0);
                
                row.innerHTML = `
                    <td><strong>${app.applicationName || 'Unknown'}</strong></td>
                    <td>${(app.currentConnections || 0).toLocaleString()}</td>
                    <td>${(app.peakConnections || 0).toLocaleString()}</td>
                    <td>${(app.totalRequests || 0).toLocaleString()}</td>
                    <td>${(app.successRate || 0).toFixed(1)}%</td>
                    <td>${(app.avgResponseTime || 0).toFixed(1)}ms</td>
                    <td>${(app.avgTps || 0).toFixed(1)} TPS</td>
                    <td>${statusBadge}</td>
                `;
                
                tbody.appendChild(row);
            });
        }
        
        // 获取状态徽章
        function getStatusBadge(responseTime) {
            if (responseTime > 100) {
                return '<span class="metric-badge metric-danger">慢</span>';
            } else if (responseTime > 50) {
                return '<span class="metric-badge metric-warning">一般</span>';
            } else {
                return '<span class="metric-badge metric-success">快</span>';
            }
        }
        
        // 更新数据状态指示器
        function updateDataStatus(isRealData = false, dataSource = 'unknown', errorMessage = null) {
            const statusElement = document.getElementById('dataStatus');
            
            if (statusElement) {
                if (errorMessage) {
                    statusElement.textContent = '错误';
                    statusElement.className = 'badge bg-danger ms-2';
                    statusElement.title = errorMessage;
                } else if (isRealData && dataSource === 'real') {
                    statusElement.textContent = '实时数据';
                    statusElement.className = 'badge bg-success ms-2';
                    statusElement.title = '显示真实的统计数据';
                } else if (dataSource === 'unavailable') {
                    statusElement.textContent = '数据不可用';
                    statusElement.className = 'badge bg-secondary ms-2';
                    statusElement.title = '统计服务不可用';
                } else if (dataSource === 'empty') {
                    statusElement.textContent = '无数据';
                    statusElement.className = 'badge bg-info ms-2';
                    statusElement.title = '暂无统计数据';
                } else {
                    statusElement.textContent = '演示数据';
                    statusElement.className = 'badge bg-warning ms-2';
                    statusElement.title = '显示模拟的演示数据';
                }
            }
        }
        
        // 更新最后更新时间
        function updateLastUpdateTime() {
            const lastUpdateElement = document.getElementById('lastUpdate');
            if (lastUpdateElement) {
                const now = new Date();
                lastUpdateElement.textContent = `更新于 ${now.toLocaleTimeString('zh-CN')}`;
            }
        }
        
        // 显示数据警告
        function showDataWarning(message) {
            // 可以在这里添加警告提示的UI逻辑
            console.warn('Data warning:', message);
        }
        
        // 显示数据错误
        function showDataError(message) {
            // 更新统计卡片显示错误状态
            document.getElementById('activeConnections').textContent = '错误';
            document.getElementById('totalRequests').textContent = '错误';
            document.getElementById('avgResponseTime').textContent = '错误';
            document.getElementById('errorRate').textContent = '错误';
            
            console.error('Data error:', message);
        }
        
        // 刷新数据
        function refreshData() {
            console.log('刷新数据...');
            
            // 旋转刷新按钮
            const refreshBtn = document.querySelector('.refresh-btn i');
            if (refreshBtn) {
                refreshBtn.classList.add('fa-spin');
            }
            
            // 加载真实数据
            Promise.all([
                loadRealTimeStats(),
                loadTrendData()
            ]).catch((error) => {
                console.error('无法加载统计数据:', error);
                updateDataStatus(false, 'error', '数据加载失败: ' + error.message);
                showDataError('统计数据加载失败，请检查服务状态或稍后重试。');
            }).finally(() => {
                if (refreshBtn) {
                    refreshBtn.classList.remove('fa-spin');
                }
                updateLastUpdateTime();
            });
        }
        
        // 加载实时统计
        function loadRealTimeStats() {
            return fetch('/api/statistics/realtime')
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    updateRealTimeStats(data);
                    updateDataStatus(true);
                })
                .catch(error => {
                    console.error('Error loading real-time stats:', error);
                    throw error;
                });
        }
        
        // 加载趋势数据
        function loadTrendData() {
            return fetch(`/api/statistics/recent/${currentTimeRange}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data && Array.isArray(data.data)) {
                        updateTrendCharts(data.data);
                    } else if (Array.isArray(data)) {
                        updateTrendCharts(data);
                    } else {
                        throw new Error('Invalid data format');
                    }
                })
                .catch(error => {
                    console.error('Error loading trend data:', error);
                    throw error;
                });
        }
        
        // 更新实时统计
        function updateRealTimeStats(data) {
            document.getElementById('activeConnections').textContent = (data.activeConnections || 0).toLocaleString();
            document.getElementById('totalRequests').textContent = (data.totalRequests || 0).toLocaleString();
            document.getElementById('avgResponseTime').textContent = (data.avgResponseTime || 0).toFixed(1) + 'ms';
            document.getElementById('errorRate').textContent = (data.errorRate || 0).toFixed(1) + '%';
        }
        
        // 更新趋势图表
        function updateTrendCharts(data) {
            if (!Array.isArray(data) || data.length === 0) {
                console.warn('No trend data available');
                return;
            }
            
            // 限制数据点数量
            const maxDataPoints = 50;
            const limitedData = data.slice(-maxDataPoints);
            
            const labels = limitedData.map(item => {
                const date = new Date(item.windowStart || item.timestamp || new Date());
                return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
            });

            // 更新连接数趋势
            const connectionValues = limitedData.flatMap(item => [
                item.activeConnections || 0, 
                item.peakConnections || 0
            ]);
            const connectionMax = yAxisManager.getRange('connection', connectionValues);
            
            charts.connection.data.labels = labels;
            charts.connection.data.datasets[0].data = limitedData.map(item => item.activeConnections || 0);
            charts.connection.data.datasets[1].data = limitedData.map(item => item.peakConnections || 0);
            charts.connection.options.scales.y.max = connectionMax;
            charts.connection.update('none');

            // 更新吞吐量趋势
            const throughputValues = limitedData.flatMap(item => [
                item.tps || 0, 
                item.qps || 0
            ]);
            const throughputMax = yAxisManager.getRange('throughput', throughputValues);
            
            charts.throughput.data.labels = labels;
            charts.throughput.data.datasets[0].data = limitedData.map(item => item.tps || 0);
            charts.throughput.data.datasets[1].data = limitedData.map(item => item.qps || 0);
            charts.throughput.options.scales.y.max = throughputMax;
            charts.throughput.update('none');

            // 更新响应时间分布
            updateResponseTimeDistribution(limitedData);
            
            // 更新错误统计
            updateErrorStats(limitedData);
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('初始化统计页面...');
            
            // 先显示加载状态
            document.getElementById('activeConnections').textContent = '加载中...';
            document.getElementById('totalRequests').textContent = '加载中...';
            document.getElementById('avgResponseTime').textContent = '加载中...';
            document.getElementById('errorRate').textContent = '加载中...';
            
            // 初始化图表
            try {
                initCharts();
                console.log('图表初始化完成');
            } catch (error) {
                console.error('图表初始化失败:', error);
            }
            
            // 设置Y轴锁定状态
            try {
                toggleYAxisLock(); // 默认锁定
            } catch (error) {
                console.error('Y轴锁定设置失败:', error);
            }
            
            // 延迟加载数据
            setTimeout(() => {
                try {
                    refreshData();
                } catch (error) {
                    console.error('数据刷新失败:', error);
                    showDataError('初始数据加载失败');
                }
            }, 1000);
            
            // 设置自动刷新
            refreshInterval = setInterval(() => {
                try {
                    refreshData();
                } catch (error) {
                    console.error('自动刷新失败:', error);
                    showDataError('自动刷新失败');
                }
            }, 30000); // 每30秒刷新一次
            
            console.log('统计页面初始化完成');
        });
        
        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });
    </script>
</body>
</html>